// 用户状态管理
import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { UserInfo } from '@/types'
import { login as loginApi, mockLogin as mockLoginApi } from '@/api/auth'

let loginCallback = (success: boolean) => {}
let loginReject = () => {}
export const useUserStore = defineStore('user', () => {
  const currentUser = ref<UserInfo | null>(null)
  const isAuthenticated = ref(false)
  const token = ref<string | null>(null)
  const showLogin = ref(false)

  // 模拟登录
  const mockLogin = async () => {
    try {
      // 这里应该调用实际的登录API
      const response = await mockLoginApi()

      const { data } = response

      currentUser.value = {
        name: 'admin',
        ...data
      }
      isAuthenticated.value = true
      token.value = currentUser.value?.tokenValue || ''

      // 保存到sessionStorage
      sessionStorage.setItem('token', token.value)
      sessionStorage.setItem('user', JSON.stringify(currentUser.value))
      showLogin.value = false
      loginCallback(true)
      return currentUser.value
    } catch (error) {
      console.log(error)
      showLogin.value = false
      loginCallback(false)
      throw new Error('登录失败')

    }
  }

  const isMockLogin = () => {
    const searchParams = new URLSearchParams(location.search)
    let sign = searchParams.get('sign')
    if (!sign) {
      return false
    }
    sign = sign.padEnd(13, '0')
    const now = Date.now()
    const delay = 10 * 60 * 1000
    return Math.abs(now - Number(sign)) < delay
  }

  // 登录
  const login = () => {
    if (!isMockLogin()) {
      showLogin.value = true
    }

    return new Promise<boolean>((resolve, reject) => {
      loginCallback = (success) => {
        resolve(success)
      }
      loginReject = reject
      if (isMockLogin()) {
        mockLogin()
      }
    })
  }

  const cancelLogin = () => {
    showLogin.value = false
    loginCallback(false)
  }

  const handleLogin = async (credentials: { username: string; password: string }) => {
    try {
      // 这里应该调用实际的登录API
      const response = await loginApi({
        username: credentials.username,
        password: credentials.password,
      })

      const { data } = response

      currentUser.value = {
        name: credentials.username,
        ...data
      }
      isAuthenticated.value = true
      token.value = currentUser.value?.tokenValue || ''

      // 保存到sessionStorage
      sessionStorage.setItem('token', token.value)
      sessionStorage.setItem('user', JSON.stringify(currentUser.value))
      showLogin.value = false
      loginCallback(true)
      return currentUser.value
    } catch (error) {
      console.log(error)
      showLogin.value = false
      loginCallback(false)
      throw new Error('登录失败')

    }
  }

  // 登出
  const logout = () => {
    currentUser.value = null
    isAuthenticated.value = false
    token.value = null

    // 清除localStorage
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('user')
  }

  // 初始化用户状态
  const initUser = () => {
    const savedToken = sessionStorage.getItem('token')
    const savedUser = sessionStorage.getItem('user')

    if (savedToken && savedUser) {
      token.value = savedToken
      currentUser.value = JSON.parse(savedUser)
      isAuthenticated.value = true
    }
  }

  return {
    currentUser,
    isAuthenticated,
    token,
    showLogin,
    login,
    cancelLogin,
    handleLogin,
    logout,
    initUser,
    isMockLogin,
  }
})
